<template>
     <qh-tabbar-page-view current="0" :showNavbar="false" :tabbarShadow="bottomNavigation">
          <view class="conteiner diy-template flex-column" :style="{
			'background-color':getTopBackGround
		}">
               <qh-navbar :title="PageData.titleBarData.data.pageText" v-if="PageData.titleBarData.data.barStatus" :color="PageData.titleBarData.data.barFontColor">
               </qh-navbar>
               <view v-for="(item,index) in PageData.compontentData" :key="index" v-if="item.sign === 'diy-float' || item.sign === 'diy-dialog' || item.sign === 'diy-bar'">
                    <diy-float v-if="item.sign === 'diy-float'" :componentData="item.data" @callback="callback"></diy-float>
                    <diy-dialog v-if="item.sign === 'diy-dialog'" :merchant="1" :componentData="item.data" @callback="callback" @toAddToCar="toAddToCar" @getSku="getSku"></diy-dialog>
                    <block v-if="item.sign === 'diy-bar'">
                         <view class="diy-sticky" :style="{
						'top':stickyTopObject['diy-bar-'+index].offSetTop+'px'
					}" v-if="scrollTop>0 && item.data.sticky && scrollTop > stickyTopObject['diy-bar-'+index].scrollTop">
                              <mer-diy-bar :autoHieght="index==0 && item.sign=='diy-bar' && PageData.titleBarData.data.barStatus==0 ? autoHieght : 0" :componentData="item" @callback="callback"></mer-diy-bar>
                         </view>
                    </block>
               </view>

               <qh-scroll-view parent-el-name=".flex-column" :barStatus="PageData.titleBarData.data.barStatus" :barStatusHeight="navbarHeight" @init="initScroll" @scrolltoupper="scrollTop=0" :throttle="false" scroll-y @scroll="onScroll" refresher-enabled @refresherrefresh="onPagePullDownRefresh" :refresher-triggered="isRefresh" refresher-background="transparent">
                    <view class="tabbar-page-bottom" :style="getBackGround">
                         <block v-for="(item,index) in PageData.compontentData" :key="index">
                              <view class="diy-bar-wrap" v-if="item.sign === 'diy-bar'" :id="'diy-bar-'+index" :data-index="index">
                                   <mer-diy-bar :componentData="item" @callback="callback" @toAddToCar="toAddToCar" @getSku="getSku" :autoHieght="index==0 && item.sign=='diy-bar' && PageData.titleBarData.data.barStatus==0 ? autoHieght : 0"></mer-diy-bar>
                              </view>
                              <diy-img v-if="item.sign === 'diy-img'" :componentData="item" @callback="callback"></diy-img>
                              <diy-swiper v-if="item.sign === 'diy-swiper'" :componentData="item" @callback="callback"></diy-swiper>
                              <diy-text v-if="item.sign === 'diy-text'" :componentData="item" @callback="callback"></diy-text>
                              <diy-btn v-if="item.sign === 'diy-btn'" :componentData="item" @callback="callback"></diy-btn>
                              <diy-word v-if="item.sign === 'diy-word'" :componentData="item" @callback="callback"></diy-word>
                              <diy-goods ref="diyGoodsRef" :merchant="1" v-if="item.sign === 'diy-goods'" :componentData="item" @callback="callback" @toAddToCar="toAddToCar" @getSku="getSku"></diy-goods>
                              <diy-video v-if="item.sign === 'diy-video'" :componentData="item" @callback="callback"></diy-video>
                              <diy-wrap v-if="item.sign == 'diy-wrap'" :componentData="item.data.componentData" :config="item.data.config" @callback="callback">
                              </diy-wrap>
                              <diy-doub-wrap v-if="item.sign == 'diy-doub-wrap'" :componentData="item.data.componentData" :config="item.data.config" @callback="callback">
                              </diy-doub-wrap>
                              <diy-notice v-if="item.sign === 'diy-notice'" :componentData="item" @callback="callback"></diy-notice>
                              <diy-navigate v-if="item.sign === 'diy-navigate'" :componentData="item" @callback="callback"></diy-navigate>
                              <!--营销组件-->
                              <diy-coupon :cityCode="cityCode" v-if="item.sign === 'diy-coupon'" :componentData="item" @callback="callback"></diy-coupon>
                              <diy-gift-card v-if="item.sign === 'diy-gift_card'" :componentData="item" @callback="callback"></diy-gift-card>
                              <mer-diy-live v-if="item.sign === 'diy-live'" :componentData="item" @callback="callback"></mer-diy-live>

                         </block>
                    </view>
               </qh-scroll-view>
               <!-- 选择规格弹窗 -->
               <block v-if="showSelectSku">
                    <choose-sku :sku="sku" :goodsinfo="goods" goodsType="1" @close="closeSku" zIndex="2147483647"></choose-sku>
               </block>
          </view>
     </qh-tabbar-page-view>
</template>
<script>
var app = getApp().globalData
import merDiyBar from "@/pages/mer/tabbar/home/components/diy_componets/mer-diy-bar/mer-diy-bar.vue"
import diyImg from "@/pages/store/components/diy-img/diy-img"
import diySwiper from "@/pages/store/components/diy-swiper/diy-swiper"
import diyText from "@/pages/store/components/diy-text/diy-text"
import diyBtn from "@/pages/store/components/diy-btn/diy-btn"
import diyWord from "@/pages/store/components/diy-word/diy-word"
import diyGoods from "@/pages/store/components/diy-goods/diy-goods"
import diyVideo from "@/pages/store/components/diy-video/diy-video"
import diyWrap from "@/pages/store/components/diy-wrap/diy-wrap"
import diyDoubWrap from "@/pages/store/components/diy-doub-wrap/diy-doub-wrap"
import diyNotice from "@/pages/store/components/diy-notice/diy-notice"
import diyNavigate from "@/pages/store/components/diy-navigate/diy-navigate"
import diyCoupon from "@/pages/store/components/diy-coupon/diy-coupon"
import diyFloat from "@/pages/store/components/diy-float/diy-float"
import diyDialog from "@/pages/store/components/diy-dialog/diy-dialog"
import diyGiftCard from "@/pages/store/components/diy-gift_card/diy-gift_card"
import merDiyLive from "@/pages/mer/tabbar/home/components/diy_componets/mer-diy-live/mer-diy-live.vue"
import qhScrollMixin from "@/components/qh-scroll-view/mixins.js";
export default {
     mixins: [qhScrollMixin], // 使用mixin
     components: {
          merDiyBar,
          diyImg,
          diySwiper,
          diyText,
          diyBtn,
          diyWord,
          diyGoods,
          diyVideo,
          diyWrap,
          diyDoubWrap,
          diyNotice,
          diyNavigate,
          diyCoupon,
          diyFloat,
          diyDialog,
          diyGiftCard,
          merDiyLive
     },
     props: {
          "pageContent": {
               type: Object,
               default: {}
          },
          "bottomNavigation": {
               type: Boolean,
               default: true
          }

     },
     data () {
          return {
               PageData: {}, // 装修数据
               PageDataState: 0,
               headerHeight: 0, // 头部高度
               diyHeadTop: "", // DIy头部高度
               capsuleHeigth: "",
               stickyTopObject: [],
               page_id: "",
               storeList: [], // 门店列表数据
               phone: "", // 手机号
               storeName: "", // 门店名称
               store_id: 0,
               showSelectSku: false,
               sku: {},
               goods: {},
               isRefresh: false,
               scrollTop: 0, // 页面高度
               //#ifdef MP-ALIPAY
               cityCode: '', //用户城市编码
               //#endif
          }
     },
     computed: {
          getTopBackGround () {
               if (this.PageData.compontentData && this.PageData.compontentData[0]['sign'] == "diy-bar") {
                    return this.PageData.compontentData[0]['data'].barBgColor;
               }
          },
          // 获取页面背景图或者背景颜色
          getBackGround () {
               if (this.PageDataState == 1) {
                    if (this.PageData.titleBarData.data.backgroundType == "color") {
                         return "background-color:" + this.PageData.titleBarData.data.pageBackgroundColor;
                    } else {
                         return "background-position:0px 0px;background-image:url(" +
                              this.PageData.titleBarData
                                   .data.backgroundImg + ")";
                    }
               }
          },
          // 页面高度
          autoHieght () {
               return this.$store.statusBarHeight;
          },
          // 状态栏高度
          navbarHeight () {
               if (this.PageDataState == 1) {
                    let navbarHeight = 0
                    if (this.PageData.titleBarData.data.barStatus) {
                         navbarHeight = 44 + this.$store.statusBarHeight;
                    }
                    return navbarHeight;
               }
          }

     },
     watch: {
          "PageData.titleBarData.data": {
               immediate: true,
               handler (n) {
                    if (this.PageDataState == 1) {
                         uni.setNavigationBarColor({
                              // #ifdef MP-WEIXIN
                              frontColor: n.systemIconColor == 1 ? "#000000" : "#ffffff",
                              // #endif
                              backgroundColor: n.systemIconColor == 1 ? "#ffffff" : "#000000",
                         });
                    }
               }
          }
     },
     methods: {
          //调用了diyGoods组件方法
          doSomething () {
               this.$refs.diyGoodsRef[0].getDataList()
          },

          // 判断是否是浮动组件
          checkOtherCompontent (checkName) {
               if (checkName == "diy-float" || checkName == "diy-dialog" || checkName == "diy-bar") {
                    return true;
               } else {
                    return false;
               }
          },
          onShows () {
               // 获取父级页面的值
               this.storeList = this.$root.storeList;
               this.phone = this.$root.phone;
               this.storeName = this.$root.storeName;
               this.cityCode = this.$root.cityCode;
               this.store_id = this.$root.store_id;
               this.page_id = this.$root.page_id;
               this.onPageLoad();
          },
          openDialog (data) {
               const dialogId = data['value'];
               let compontentIndex = -1;
               const flag = this.PageData.compontentData.some((item, index) => {
                    if ((item['sign'] === 'diy-dialog') && item['data'] && (item['data']['id'] === dialogId)) {
                         compontentIndex = index;
                         return true;
                    }
               });
               if (flag) {
                    // 判断当前是否打开对话框，如果是，表示是从对话框内的点击打开新对话框
                    // 获取 层级最高的对应层级
                    let dialogZindex = 1960;
                    this.PageData.compontentData.forEach((item, index) => {
                         if (item['sign'] === 'diy-dialog') {
                              if (item['data']['realVisible'] === 1) {
                                   // 当前是打开的
                                   if (item['data']['setDialogZindex'] > dialogZindex) {
                                        dialogZindex = item['data']['setDialogZindex']
                                   }
                                   if (item['data']['dialogZindex'] > dialogZindex) {
                                        dialogZindex = item['data']['dialogZindex']
                                   }
                              }
                         }
                    });
                    dialogZindex += 1;
                    this.setData({
                         ['PageData.compontentData[' + compontentIndex + '].data.realVisible']: 1,
                         ['PageData.compontentData[' + compontentIndex + '].data.setDialogZindex']: dialogZindex,
                    })
               }
          },
          // 关闭弹窗
          closeDialog (data) {
               const dialogId = data['value'];
               let compontentIndex = -1;
               const flag = this.PageData.compontentData.some((item, index) => {
                    if ((item['sign'] === 'diy-dialog') && item['data'] && (item['data']['id'] === dialogId)) {
                         compontentIndex = index;
                         return true;
                    }
               });
               if (flag) {
                    this.setData({
                         ['PageData.compontentData[' + compontentIndex + '].data.realVisible']: 2,
                         ['PageData.compontentData[' + compontentIndex + '].data.setDialogZindex']: 0,
                    })
                    this.$store.closeDialogList.push(dialogId);
               }
          },

          // 页面重新获取数据
          onPagePullDownRefresh () {
               this.isRefresh = true;
               this.getPageData(this.store_id, this.page_id);
          },
          callback (e) {
               const detail = e.detail;
               if (typeof this[detail.method] === 'function') {
                    this[detail.method](detail.data);
               }
          },
          onPageLoad () {
               this.PageData = this.optimizePageData(this.$root.page_content, this.$store.closeDialogList);
               console.log(this.PageData)
               this.PageDataState = 1;
               this.$nextTick(() => {
                    this.stickyTop();
               })
          },
          optimizePageData (data, closeDialogList) {
               const { compontentData, ...otherData } = JSON.parse(data);
               const newCompontentData = compontentData.map(res => {
                    if (res.sign === "diy-dialog" && res.data["realVisible"] == 1) {
                         var index = closeDialogList.indexOf(res.data.id);
                         if (index >= 0) {
                              res = Object.assign({}, res, { data: { realVisible: 2 } });
                         }
                    }
                    return res;
               });
               return { ...otherData, compontentData: newCompontentData };
          },
          // 获取装修的DIY数据
          async getPageData (store_id, page_id) {
               let diy_data, url;
               diy_data = {
                    store_id: store_id
               }
               if (page_id) {
                    diy_data.page_id = page_id;
               }
               url = '/DiyStore/Api/getMerchantPageData';
               try {
                    const {
                         status,
                         data,
                         message,
                    } = await this.$request(url, diy_data);
                    if (status == 1) {
                         this.PageData = this.optimizePageData(data.content, this.$store.closeDialogList);
                         this.PageDataState = 1;
                         this.$nextTick(() => {
                              this.stickyTop();
                         });

                         if (this.isRefresh) {
                              this.isRefresh = false;
                              uni.showToast({
                                   title: '刷新成功',
                                   duration: 800,
                              });
                         }
                    }
               } catch (err) { }
          },
          stickyTop () {
               let that = this;
               const Arr = [];
               [...this.PageData.compontentData].forEach((item, index) => {
                    if (item.sign === 'diy-bar' && item.data.sticky) {
                         Arr.push(this.getRect('#diy-bar-' + index));
                    }
               });
               Promise.all(Arr).then((resArr) => {
                    const stickyTopObject = {};
                    let offSetTop = 0;
                    let lastHeight = 0;
                    resArr.forEach((item, index) => {
                         if (item === null) {
                              offSetTop = -1
                         } else {
                              if (offSetTop) {
                                   offSetTop = offSetTop;
                              } else {
                                   offSetTop = that.navbarHeight;
                              }
                              const totalHeight = item.height;
                              item.offSetTop = offSetTop;
                              stickyTopObject[item.id] = item;
                              item.scrollTop = item.top - totalHeight - lastHeight;
                              offSetTop += totalHeight;
                              lastHeight = totalHeight;
                         }
                    });

                    if (offSetTop >= 0) {
                         that.stickyTopObject = stickyTopObject;

                    } else {
                         that.errorNum = that.errorNum ? that.errorNum : 0;
                         that.errorNum++;
                         return Promise.reject();
                    }
               }).catch(() => {
                    if (that.errorNum && that.errorNum > 10) { } else {
                         that.$nextTick(() => {
                              that.stickyTop();
                         })
                    }
               })
          },
          // 监听滚动事件
          onScroll (event) {
               this.scrollTop = event.detail.scrollTop;
          },
          //添加到购物车
          async toAddToCar (data) {
               const res = await this.$mutations.setShoppingCar({
                    goods_id: data.goods_id,
                    num: 1,
               });
               if (res) {
                    this.sku.canChangeCarNum = 1;
                    this.sku.canChangeAddNum = true;
                    this.showSelectSku = false;
               }
          },
          //取消选择规格
          closeSku () {
               this.showSelectSku = false;
          },
          //获取SKU
          async getSku (goods) {
               console.log("商品的数据", goods);
               if (goods.attribute_state == 2) {
                    goods.goods_num = 999;
                    goods.goods_image = goods.goods_img;
                    goods.attribute = goods.attribute_state;
                    this.goods = goods;
                    this.showSelectSku = true;
               }
          },
          getRect (selector) {
               return new Promise(resolve => {
                    uni.createSelectorQuery().in(this).select(selector).boundingClientRect(rect => {
                         resolve(rect);
                    }).exec();
               });
          }
     }
}
</script>
<style lang="scss">
// .diy-bar-wrap{
// 	>mer-diy-bar{
// 		>view{
// 			// background-color: #fff!important;
// 			padding-bottom: 80px!important;
// 			border-radius: 0 0 50px 50px;
// 		}
// 	}
// }
.diy-template {
     width: 100%;
     height: 100vh;
     background-color: #f6f6f6;

     .diy-template-content {
          overflow-y: scroll;
     }
}

.page-static {
     text-align: center;
     color: #999999;
     line-height: 120rpx;
     padding-bottom: 40rpx;
     font-size: 24rpx;
}

.s {
     text-decoration: line-through;
}

.buying {
     // pos
     width: 50%;
     padding: 25rpx 0;
     position: relative;
     left: 20rpx;

     i {
          font-style: normal;
          display: inline-block;
     }

     i:nth-child(1) {
          color: #333333;
          font-size: 32rpx;
          margin-bottom: 8rpx;
          font-weight: bold;
     }

     i:nth-child(2) {
          position: absolute;
          left: 36rpx;
          bottom: 23rpx;
          width: 60rpx;
          height: 6rpx;
          background-color: #ff6433;
          border-radius: 20px;
     }
}

.pagesss {
     width: 100%;
     height: 20vh;
     background-color: pink;
}

.diy-head {
     position: fixed;
     top: 0;
     width: 100%;
     background-color: #fff;

     .diy-local {
          position: fixed;
          top: 2vh;
     }
}

.diy-head {
     position: fixed;
     top: 0;
     width: 100%;
     background-color: #fff;

     .diy-local {
          position: fixed;
          top: 2vh;
     }
}

.diy-sticky {
     position: fixed;
     width: 100%;
     left: 0;
     z-index: 2001;
}

.draggable-box {
     min-height: 1000px;
}
</style>